#include "historymanager.h"
#include <QDateTime>
#include <QStringList>

HistoryManager::HistoryManager(QObject *parent) : QObject(parent)
{
    m_historyStore = new QSettings("AIHistory.ini", QSettings::IniFormat, this);
}

void HistoryManager::addMessage(const QString &conversationId, const QString &time,
                              const QString &question, const QString &answer)
{
    // 记录对话总数
    int count = m_historyStore->beginReadArray(conversationId);
    m_historyStore->endArray();

    // 添加新消息
    m_historyStore->beginWriteArray(conversationId);
    m_historyStore->setArrayIndex(count);
    m_historyStore->setValue("time", time);
    m_historyStore->setValue("question", question);
    m_historyStore->setValue("answer", answer);
    m_historyStore->endArray();

    // 记录对话基本信息（ID和第一条问题，用于列表显示）
    if (count == 0) {
        m_historyStore->setValue(QString("conversations/%1").arg(conversationId),
                                question.left(20) + (question.length() > 20 ? "..." : ""));
    }
}

QList<QPair<QString, QString>> HistoryManager::getMessages(const QString &conversationId)
{
    QList<QPair<QString, QString>> messages;

    int count = m_historyStore->beginReadArray(conversationId);
    for (int i = 0; i < count; ++i) {
        m_historyStore->setArrayIndex(i);
        QString question = m_historyStore->value("question").toString();
        QString answer = m_historyStore->value("answer").toString();
        messages.append(qMakePair(question, answer));
    }
    m_historyStore->endArray();

    return messages;
}

QMap<QString, QString> HistoryManager::getConversationList()
{
    QMap<QString, QString> conversations;

    QStringList convIds = m_historyStore->childGroups().filter("conversations");
    if (!convIds.isEmpty()) {
        m_historyStore->beginGroup("conversations");
        QStringList keys = m_historyStore->allKeys();
        foreach (const QString &key, keys) {
            conversations[key] = m_historyStore->value(key).toString();
        }
        m_historyStore->endGroup();
    }

    return conversations;
}

void HistoryManager::clearAllHistory()
{
    // 清除所有对话记录
    QStringList groups = m_historyStore->childGroups();
    foreach (const QString &group, groups) {
        m_historyStore->remove(group);
    }

    // 清除对话列表
    m_historyStore->remove("conversations");
}

void HistoryManager::clearConversation(const QString &conversationId)
{
    m_historyStore->remove(conversationId);
    m_historyStore->remove(QString("conversations/%1").arg(conversationId));
}
